import React, { useEffect, useState } from 'react';
import { Table, Tag, Empty, message, Button, Modal } from 'antd';
import { getOrderDetail, payOrder, cancelOrder } from '../api/order';

const Orders: React.FC = () => {
  const userStr = localStorage.getItem('user');
  const user = userStr ? JSON.parse(userStr) : {};
  const [orders, setOrders] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  const fetchOrders = (pageNum = 1, size = 10) => {
    getOrderDetail(pageNum, size).then(res => {
      if (res.data && res.data.data && Array.isArray(res.data.data.records)) {
        setOrders(res.data.data.records);
        setTotal(res.data.data.total || 0);
      } else {
        setOrders([]);
        setTotal(0);
      }
    }).catch(() => {
      message.error('获取订单失败');
    });
  };

  const handleCancelOrder = (orderId: number) => {
    Modal.confirm({
      title: '确认取消订单',
      content: '确定要取消这个订单吗？',
      onOk: async () => {
        try {
          await cancelOrder(orderId);
          message.success('订单已取消');
          fetchOrders(page, pageSize);
        } catch (error) {
          message.error('取消订单失败');
        }
      }
    });
  };

  const columns = [
    { title: '商品名称', dataIndex: 'productName', key: 'productName' },
    { title: '数量', dataIndex: 'quantity', key: 'quantity' },
    { title: '金额', dataIndex: 'amount', key: 'amount', render: (v: number) => `￥${v}` },
    { 
      title: '订单状态', 
      dataIndex: 'status', 
      key: 'status', 
      render: (status: number) => {
        switch (status) {
          case 0:
            return <Tag color="gray">已取消</Tag>;
          case 1:
            return <Tag color="red">未支付</Tag>;
          case 2:
            return <Tag color="green">已支付</Tag>;
          default:
            return <Tag color="default">未知状态</Tag>;
        }
      }
    },
    { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => {
        if (record.status === 1) {
          return (
            <div style={{ display: 'flex', gap: '8px' }}>
              <Button
                type="primary"
                size="small"
                onClick={async () => {
                  try {
                    await payOrder({
                      orderId: record.id,
                      amount: record.amount,
                      productId: record.productId,
                      quantity: record.quantity,
                      userId: record.userId,
                    });
                    message.success('支付成功');
                    fetchOrders(page, pageSize);
                  } catch {
                    message.error('支付失败');
                  }
                }}
              >
                去支付
              </Button>
              <Button
                type="default"
                size="small"
                danger
                onClick={() => handleCancelOrder(record.id)}
              >
                取消订单
              </Button>
            </div>
          );
        }
        return null;
      },
    },
  ];

  useEffect(() => {
    if (!user.isAdmin) {
      fetchOrders(page, pageSize);
    }
  }, [user.isAdmin, page, pageSize]);

  if (user.isAdmin) {
    return <Empty description="无数据" style={{ marginTop: 100 }} />;
  }

  return (
    <div style={{ padding: 24 }}>
      <h2>订单列表</h2>
      <Table
        rowKey="id"
        columns={columns}
        dataSource={orders}
        pagination={{
          current: page,
          pageSize,
          total,
          onChange: (p, ps) => {
            setPage(p);
            setPageSize(ps);
          },
        }}
      />
    </div>
  );
};

export default Orders; 